//
//  CityListViewController.m
//
//  Created by Big Watermelon on 11-11-10.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CityListViewController.h"
#import "ZJZXMailViewController.h"
#import "ZJZXContentViewController.h"
#import "AppDelegate.h"
#import "APService.h"
#import "NetCheckUtil.h"
@interface CityListViewController ()
@property NSUInteger curSection;
@property NSUInteger curRow;

//@property NSUInteger defaultSelectionRow;
//@property NSUInteger defaultSelectionSection;

@end

@implementation CityListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.curRow = NSNotFound;
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setBackgroundImage:[UIImage imageNamed:@"navi_backbtn"] forState:UIControlStateNormal];
    [backButton setTitle:@"" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(pressReturn) forControlEvents:UIControlEventTouchUpInside];
    backButton.frame = CGRectMake(0.0f, 0.0f, 25.0f, 25.0f);
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunchAndNotNet"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunchAndNotNet"];
        //不论有网没网，第一次启动城市列表都从本地读取
//        if (![NetCheckUtil isNetworkRunning]) {
            NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"
                                                           ofType:@"plist"];
            self.cities = [[NSDictionary alloc]
                           initWithContentsOfFile:path];
            
            self.keys = [[self.cities allKeys] sortedArrayUsingSelector:
                         @selector(compare:)];
            
            [[NSUserDefaults standardUserDefaults]setObject:self.cities forKey:kCity];//保存数据
//        }else{
//            self.cities = [[NSUserDefaults standardUserDefaults]objectForKey:kCity];
//            self.keys = [[self.cities allKeys]sortedArrayUsingSelector:@selector(compare:)];
//        }
    }else{
        self.cities = [[NSUserDefaults standardUserDefaults]objectForKey:kCity];
        self.keys = [[self.cities allKeys]sortedArrayUsingSelector:@selector(compare:)];
    }
    
    NSString* currentCity = [[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCity];
    if (currentCity) {
        NSArray *citySection;
        self.curRow = NSNotFound;
        //set table index to this city if it existed
        for (NSString* key in self.keys) {
            citySection = [self.cities objectForKey:key];
            self.curRow = [citySection indexOfObject:currentCity];
            if (NSNotFound == self.curRow)
                continue;
            //found match recoard position
            self.curSection = [self.keys indexOfObject:key];
            break;
        }
        
        if (NSNotFound != self.curRow) {
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.curRow inSection:self.curSection];
            [self.tbView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
            
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [self.keys count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSString *key = [self.keys objectAtIndex:section];
    NSArray *citySection = [self.cities objectForKey:key];
    return [citySection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    NSString *key = [self.keys objectAtIndex:indexPath.section];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    } else {
        
    }
    
    // Configure the cell...
//    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont systemFontOfSize:18];
    NSArray *citiesInLetter = [self.cities objectForKey:key];
    NSLog(@"====>Cities:%@\n",citiesInLetter);
    NSDictionary *cityDic = [citiesInLetter objectAtIndex:indexPath.row];
    cell.textLabel.text = [cityDic objectForKey:@"name"];
    
    if (self.curRow != NSNotFound) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
        
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{  
    NSString *key = [self.keys objectAtIndex:section];
    return key;  
}  

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView  
{  
    return self.keys;
} 


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSIndexPath *prevIndexPath = [NSIndexPath indexPathForRow:self.curRow inSection:self.curSection];
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:prevIndexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.curSection = indexPath.section;
    self.curRow = indexPath.row;
    
    NSString* key = [self.keys objectAtIndex:self.curSection];
    NSArray *citiesInLetter = [self.cities objectForKey:key];
    NSDictionary *cityDic = [citiesInLetter objectAtIndex:self.curRow];
    NSString *currentCity = [cityDic objectForKey:@"name"];
    NSString *currentCityID = [cityDic objectForKey:@"id"];
    NSLog(@"====>CurrentCity:%@\n====>CurrentID:%@",currentCity,currentCityID);
    [[NSUserDefaults standardUserDefaults]setObject:currentCityID forKey:kCurrentCityID];
    [[NSUserDefaults standardUserDefaults]setObject:currentCity forKey:kCurrentCity];
    if (self.delegate && [self.delegate respondsToSelector:@selector(citySelectionUpdate:selectedCityID:)]) {
        [self.delegate citySelectionUpdate:currentCity selectedCityID:currentCityID];
    }
    
    if (self.dismissStyle == Mail){
        if (self.delegate && [self.delegate respondsToSelector:@selector(pushMailViewController)]) {
            [self.delegate pushMailViewController];
        }
        
    }
    [self dismissModalViewControllerAnimated:YES];
}

- (void)pressReturn{
    //notify delegate user selection if it different with default
    if (![[NSUserDefaults standardUserDefaults]objectForKey:kCurrentCityID]) {
        if (self.dismissStyle == LoanEnquiry) {
            AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [appDelegate.tabbarVC setSelectedIndex:appDelegate.tabbarLastIndex];
        }
    }
    
    [self dismissModalViewControllerAnimated:YES];
}

//- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
//    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
//}


@end
